import axios from 'axios'
import store from '@/store'
import Vue from 'vue'
import { callType } from '@/utils'
import { getToken, setToken } from '@/utils/auth'
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: baseUrl, // 本地服务器

  baseURL: process.env.VUE_APP_BASEURL,
  timeout: 60000, // request timeout
  withCredentials: true
})

service.interceptors.request.use(
  config => {
    const token = getToken()
    for (const key in config.data) {
      if (!config.data[key] && config.data[key] !== 0) {
        if (config.url.indexOf('update') === -1 && config.url.indexOf('insertAnswerExam') === -1) {
          delete config.data[key]
        }
      }
    }
    if (token) {
      config.headers.token = token
    }

    if (config.url.indexOf('download') > -1) {
      config.responseType = 'blob'
    }

    if (config.method.toLowerCase() === 'get') {
      config.params = config.data
    }
    return config
  },
  error => {
    console.log('error=>', error)
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  response => {
    const vueObj = new Vue()
    const res = response.data
    if (res && res.token) {
      setToken(res.token)
    }
    if (res.code !== 0) {
      if (res.code === 401) {
        store.dispatch('resetToken').then(() => {
          location.reload()
        })
      }
      if (callType(res) === 'Blob') {
        return URL.createObjectURL(res)
      }
      if (res.msg) {
        vueObj.$toast(res.msg)
      } else {
        vueObj.$toast('数据请求失败!')
      }

      return Promise.reject(res.msg || 'Error')
    } else {
      return res
    }
  },
  error => {
    const vueObj = new Vue()
    vueObj.$toast('err' + error)
    return Promise.reject(error)
  }
)
export default service
